import sys, re, os

def parse(filename):
    lines = open(sys.argv[1]).read().split('\n')

    #parse
    lst_fullpath = []
    for line in lines:
        if len(line) == 0:
            continue

        res = re.search(r'<ClCompile Include="([^"]+)"', line)
        if res:
            relpath = res.groups()[0]
            abspath = os.path.abspath(relpath)
            lst_fullpath.append(relpath)

    #group
    lst_file = []
    map_path = {}
    for abspath in sorted(lst_fullpath):
        (fpath, fname) = os.path.split(abspath)
        if fpath not in map_path:
            lst_file = []
            map_path[fpath] = lst_file
        lst_file.append(fname)

    return map_path

#fmt
clcompile_fmt_file = '\t.\\%s'
clcompile_fmt_cl1 = '''
{%s}.c{.}.obj:
\tcl $(CFLAGS) $<
'''
clcompile_fmt_cl2 = '''
%s:%s
\tcl $(CFLAGS) %s /Fo%s
'''

def generate_fmt1(map_path):
    for fpath in map_path:
        print 'OBJS = \\'
        lst_file = map_path[fpath]
        i = 0
        nr_files = len(lst_file)
        for fname in lst_file:
            msg = clcompile_fmt_file % re.sub(r'\.c$', '.obj', fname)
            if i + 1 < nr_files:
                print msg, '\\'
            else:
                print msg
            i += 1

    for fpath in map_path:
        print clcompile_fmt_cl1 % fpath

def generate_fmt2(map_path):
    lst_objs = []
    for fpath in map_path:
        lst_file = map_path[fpath]
        for fname in lst_file:
            srcname = '%s\\%s' % (fpath, fname)
            objname = re.sub(r'\.c$', '', srcname)
            objname = objname.replace('\\', '_s_')
            objname = objname.replace('.', '_d_')
            objname += '.obj'
            lst_objs.append((objname, srcname))

    #create files list
    fout = open('files.mak', 'w')
    fout.write('%s\n' % 'OBJS = \\')
    i = 0
    nr_files = len(lst_objs)
    for (objname, srcname) in lst_objs:
        msg = clcompile_fmt_file % objname
        if i + 1 < nr_files:
            fout.write('%s \\\n' % msg)
        else:
            fout.write('%s\n' % msg)
        i += 1
    fout.write('\n')
    fout.close()

    #create build rule
    fout = open('build.mak', 'w')
    for (objname, srcname) in lst_objs:
        msg = clcompile_fmt_cl2 % (objname, srcname,
                srcname, objname)
        fout.write('%s\n' % msg)
    fout.write('\n')
    fout.close()

map_path = parse(sys.argv[1])
generate_fmt2(map_path)
